/*
The MIT License (MIT)

Copyright (c) 2013 Mike Dapiran, Brian May, Richard Pospesel, and Bert Wierenga

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software 
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "MeshRenderer.h"
#include <Windows.h>
#include <D3DX11.h>
#include "../HLSLCPPDeclarations/Lighting.fx"

#include "../Content/MeshFilter.h"
#include "Hogshead.Common.h"

namespace Hogshead
{
	namespace DX11Rendering
	{
		ComponentCPP(Hogshead::DX11Rendering::MeshRenderer)


		int MeshRenderer::ID = 0;

		MeshRenderer::MeshRenderer(void) : _meshes(NULL), _needs_lighting(true), 
		_specular_exponent(1.5f), _techniques(10)
		{			
			_never_cull = false;
			_name = "";
			// register message callback
			this->registerMessageCallback<ConstantBufferModifier>(handle_constant_buffer_modifier_message);
			_dx11_director = NULL;
			_process_specific_data = NULL;

			_particle_system = false;
			_my_id = MeshRenderer::ID++;

			_registered = false;

			_taken = false;
		}
		
		MeshRenderer::~MeshRenderer(void)
		{
			
		}
		
		const ConstantBufferGroup& MeshRenderer::constantBufferGroup() const
		{
			return _constant_buffer_group;
		}

		ConstantBufferGroup& MeshRenderer::constantBufferGroup() 
		{
			return _constant_buffer_group;
		}

		const MeshFilter* MeshRenderer::meshFilter() const
		{
			return _meshes;
		}

		void MeshRenderer::handle_constant_buffer_modifier_message(IMessageReceiver* receiver, IMessage* message)
		{
			MeshRenderer* me = (MeshRenderer*)receiver;
			me->_constant_buffer_group.handleConstantBufferModifier(message->as<ConstantBufferModifier>());
		}


		

		Technique* MeshRenderer::getTechnique(int process_handle)
		{
			
			return _techniques[process_handle];
		}

		void MeshRenderer::initialize()
		{

			_dx11_director = (DX11Director*)getParentScene()->getDirector("DX11Director");
			if( _dx11_director )
			{
				_dx11_director->registerComponent( this );
				_registered = true;
			}
			else
			{
				error("MeshRenderer component requires a DX11Director");
			}
		}

		void MeshRenderer::finalize()
		{
			auto& iter = _techniques.getEnumerator();
			while(iter.moveNext())
			{
				ContentLibrary::release( iter.current().second );
			}

			_techniques.clear();

			if( _meshes )
			{
				ContentLibrary::release( _meshes );
				_meshes = NULL;
			}

			_needs_lighting = false;

			_constant_buffer_group.clear();

			if(_dx11_director)
				_dx11_director->unregisterComponent(this);

			if(this->_process_specific_data)
				delete this->_process_specific_data;

		}

		IComponent* MeshRenderer::clone() const
		{
			MeshRenderer* clone = Factory::acquire<MeshRenderer>();
			//get references for the content from the content library
			//get the meshfilter
			if(_meshes)
				clone->_meshes = ContentLibrary::getContent<MeshFilter>(_meshes->getKey());
			else
				clone->_meshes = NULL;
			
			
			//get pointers to the techniques

			auto* iter = _techniques.getNewEnumerator();

			while(iter->moveNext())
			{
				int first = iter->current().first;
				Technique* second = ContentLibrary::getContent<Technique>( iter->current().second->getKey());
				clone->_techniques.add(first, second);
			}

			delete iter;

			//copy the constant buffer group
			clone->_constant_buffer_group = _constant_buffer_group;

			clone->_name = this->_name;

			//potentially copy lighting
			clone->_needs_lighting = _needs_lighting;
			clone->_specular_exponent = _specular_exponent;

			if(this->_process_specific_data)
				clone->_process_specific_data = this->_process_specific_data->clone(); 
			else
				clone->_process_specific_data = NULL;

			clone->_particle_system = this->_particle_system;

			clone->_never_cull = this->_never_cull;

			clone->_my_id = this->_my_id;

			clone->_taken = false;

			return clone;
		}

		IComponent* MeshRenderer::readXML(const String& in_xml)
		{
			TiXmlDocument document;
			document.Parse(in_xml);
			
			TiXmlElement* root_element = document.RootElement();
			String root_tag(root_element->Value());

			if( root_element )
			{
				if( root_tag.equals( "Component" ) && String::equals(root_element->Attribute("type"), "MeshRenderer" ) )
				{
					TiXmlNode* child_node = NULL;
					TiXmlElement* child_element;

					root_element->QueryBoolAttribute("needs_lighting", &_needs_lighting);
					root_element->QueryFloatAttribute("specular_exponent", &_specular_exponent);

					while(child_node = root_element->IterateChildren(child_node))
					{
						child_element = child_node->ToElement();
						if(!child_element)
							continue;
					
						String tag(child_element->Value());
						if(tag.equals("ContentXML"))
						{
							if(String::equals(child_element->Attribute("type"), "MeshFilter") )
							{
								//get the MeshFilter we want from ContentLibrary
								_meshes = (MeshFilter*) ContentLibrary::loadAndParseContentXML( String(child_element->Attribute("path")) );
							}
							else if( String::equals(child_element->Attribute("type"), "Technique") )
							{
								//get the string for the process we register with
								int mesh_handle = -1;

								child_element->QueryIntAttribute("mesh_process_handle", &mesh_handle);

								if( mesh_handle == -1 )
									error(StringBuilder() << this->getParentGameObject()->name() << " needs a mesh process handle");

								//get the Technique we want from the ContentLibrary, create the pair 
								_techniques.add(mesh_handle,
									(Technique*) ContentLibrary::loadAndParseContentXML( String( child_element->Attribute("path")) ));
								
									
							}
						}
						else if(tag.equals("ConstantBufferGroup"))
						{
							//hand the correct xml block to our ConstantBufferGroup
							//so that it can create itself.
							_constant_buffer_group.readXML( String(*child_element) );
						}
					
					}
					
					if(!_meshes)
					{
						_meshes = (MeshFilter*) ContentLibrary::loadEmpty<MeshFilter>(this->_name, this->_name);
					}
					//if we care about lighting, then we need to get that struct and parse for some extra info.
					
					
				}

			}
			
			return this;
		}


		bool MeshRenderer::useLighting() const
		{
			return _needs_lighting;
		}

		
		void MeshRenderer::setMeshFilter(MeshFilter* in_mf)
		{
			this->_meshes = in_mf;
		}

		void MeshRenderer::setConstantBufferGroup(ConstantBufferGroup in_cbg)
		{
			this->_constant_buffer_group = in_cbg;
		}

		
		void MeshRenderer::onSetActive()
		{
			if(_registered)
				return;

			_dx11_director->registerComponent( this );
			_registered = true;
		}
		
		void MeshRenderer::onSetInactive()
		{
			if(!_registered)
				return;

			if(!this->_particle_system)
			{
				_dx11_director->unregisterComponent(this);
				_registered = false;
			}
		}
		
	}
}